$(function() {
    //主流程对象
    var mainCtrl = avalon.define({
        $id: "mainController",
        commCode: "",
        cateCode : "",
        typeId : "",
        startTime: getMinDate(-30),
        endTime: getMinDate(0),
        recordCount: 0,
        allCategory: [],
        searchRecordList: function() {
            var searchParam = {
                "pageNo": 1,
                "pageSize": 10,
                "commCode": mainCtrl.commCode,
                "cateCode": mainCtrl.cateCode,
                "typeId": mainCtrl.typeId
            }
            taskTable.search(searchParam);
        },
        queryAllCategory: function() {
            $.ajax({
                type: "post",
                dataType: "json",
                url: DI.queryMssCateList,
                success: function(data) {
                    mainCtrl.allCategory = data.data.list;
                    mainCtrl.allCategory.unshift({
                        "cateName": "全部",
                        "cateCode": ""
                    });
                    
                }
            });
        },
        addCommodity: function() {
        	window.location = "mssAddComm.html";
        },
        importCommodity: function() {
        	$("#upladFile").val("");
        	$("#popup_import").show();
        }
    });
    
    var popCtrl = avalon.define({
        $id: "popController",
        confirmType: "del",
        delCommObj: "",
        confirmSure: function() {
            var dataJson = {
                "id": popCtrl.delCommObj.id + ""
            };
            $.ajax({
                type: "post",
                dataType: "json",
                data: dataJson,
                url: DI.deleteMssCommById,
                success: function(data) {
                    $("#popup_confirm").hide();
                    if(data.retFlag == 1) {
                        PLATFORM.showTips("success", "删除成功");
                        taskTable.refresh();
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                },
                error: function(err) {
                    console.log(err)
                }
            });
        },
        uploadFile:function() {
        	if ($("#upladFile").val() == "") {
                return;
            }
            $("#load-import").show();
            $("#form_file").ajaxSubmit({
                type: "post",
                dataType: "json",
                url: DI.importMssCommodity,
                success: function(data) {
                	$("#load-import").hide();
                    if (data.retFlag == 1) {
                    	$("#popup_import").hide();
                    	var msg = data.data;
                    	if (typeof msg != "undefined" && msg.length >0) {
                    		PLATFORM.showTips("warning", msg);
                    	}
                    	// 刷新页面
                    	taskTable.searchParam.pageNo = "1";
                        taskTable.refresh();
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                    $("#upladFile").after($("#upladFile").clone().val(""));
                    $("#upladFile").remove();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                	PLATFORM.showTips("error", "服务异常,请稍后再试");
                    console.log("ajax error");
                    console.log(XMLHttpRequest);
                }
            });
        }
    });

    //表格实例化
    var taskTable = null;
    var opts = {
        targetId: "taskTable",
        templateId: "tableTask",
        settings: {
            url: DI.queryMssCommodityPage,
            ajaxType: "json",
            sourceInterface: {
                INum: "totalSize",
                IData: "list"
            },
            paginationIndexName: {
                "peerpageRows": "pageSize",
                "currentPage": "pageNo"
            },
            searchParam: {
                "commCode": mainCtrl.commCode,
                "cateCode": mainCtrl.cateCode,
                "typeId": mainCtrl.typeId
            }
        },
        customFuncs: {
            delCommodity: function(row) {
            	popCtrl.delCommObj = row;
            	$("#popup_confirm").show();
            },
            processName: function(name) {
            	if (typeof name != "undefined" && name != null && name.length >15) {
            		return name.substring(0, 12) + "...";
            	}
            	return name;
            },
            getUrl: function(commcode) {
                var codeLen = commcode.length;
                if (codeLen == 18) {
                    return DI.imageSplitURL + commcode + "_1_100x100.jpg";
                } else {
                    var curLen = 18 - codeLen,
                        curZero = "";
                    for (var i = 0; i < curLen; i++) {
                        curZero += "0";
                    }
                    return DI.imageSplitURL + curZero + "" + commcode + "_1_100x100.jpg";
                }
                return "";
            },
            queryPrice: function(commCode, mertCode) {
            	var url = DI.getMssPrice;
            	// 置换URL
            	url = url.replace("{cmmdtyCode}", commCode);
            	url = url.replace("{bizCode}", mertCode);
            	// 查询价格
            	$.ajax({
                    type: "GET",
                    dataType: "jsonp",
                    url: url,
                    jsonp: false,
                    jsonpCallback:"priceBack",
                    success: function(data) {
                    	var sources = taskTable.table.sources;
                    	// 转换成MAP结构
                    	var dataMap = new Object();
                        // 商品编码+商家编码组成KEY
                    	for (var item in data) {
                    		dataMap[data[item].cmmdtyCode + data[item].bizCode] = data[item];
                    	}
                    	// 迭代记录
                    	for (var item in sources) {
                    		// 价格处理
                    		var key =opts.customFuncs.initCommCode(sources[item].commCode) 
                    			+ opts.customFuncs.initMertCode(sources[item].mertCode);
                    		var d = dataMap[key];
                    		if (typeof d == "undefined" || typeof d.price == "undefined" || d.price == "") {
                    			sources[item].price = "售罄";
                    		} else {
                    			sources[item].price = d.price;
                    		}
                    	}
                    },
                    error: function(err) {
                        console.log(err)
                    }
                });
            },
            initCommCode:function(commCode) {
            	var cc = commCode;
            	if (typeof cc != "undefined") {
            		// 18位
            		cc = "000000000000000000" + cc;
            		return cc.substring(cc.length-18, cc.length);
            	}
            	return commCode;
            },
            initMertCode:function(mertCode) {
            	var mc = mertCode;
            	if (typeof mc == "undefined" || mc == "0" || mc.length != 10) {
            		// 10位自营
            		return "0000000000";
            	}
            	return mertCode;
            }
        },
        dataFilter : function(rows){
        	//记录总数 console.log(taskTable.table.returnData.data.totalSize);
        	var commCodes = [];
        	var mertCodes = [];
        	if (rows.length > 0) {
        		// 拼装商品编码,商家编码集合
            	for (var item in rows) {
            		// 格式化商品编码
            		commCodes.push(opts.customFuncs.initCommCode(rows[item].commCode));
            		// 格式化商家编码
            		mertCodes.push(opts.customFuncs.initMertCode(rows[item].mertCode));
            	}
            	// 逗号分隔,执行查询价格
            	opts.customFuncs.queryPrice(commCodes.join(","), mertCodes.join(","));
        	}
        	return rows;
        }
    };
    
    taskTable = SwiftUI.swiftTable.getInstance(opts);
    
    mainCtrl.queryAllCategory();
    avalon.scan();
});